#
# Package.
#

package iSOCK::Model::Root;

#
# Parent.
#

use Moose;
use namespace::autoclean;

BEGIN { extends 'Catalyst::Model' }

#
# Dependencies.
#

use IPC::Run;

#
# Subs.
#

sub delete_session_keys {
  my ( $self, $option ) = @_;
  
  my $c       = $option->{c};
  my $session = $c->session;
  
  delete $session->{$_} for $self->session_keys;
  
  $c->log->debug ( "Deleted session keys (" . ref ( $self ) . ")" . ( $option->{reason} ? ": $option->{reason}" : "" ) . "." );
  
  $self;
}

sub delete_session_files {
  shift;
}

sub spawn {
  my ( $self, $c, $command, $log, $env ) = @_;
  
  ( my $said_command = $command ) =~ s/ ( \s+ --(file_)?indent \s+ \d+ | \s+ --(repository_)?password \s+ '[^']+' ) //gx;
  
  $log->say_n_right ( "Spawning \"$said_command\" command..." );

  my $session_path = $c->session->{session_path};
  my @commands     = split m/\s+/, $command;
  my $tool         = shift @commands;
  my $log_file     = "$session_path/$tool.log";
  
  my $sock_root = $c->path_to ( 'root', 'SOCK' );
  
  unshift @commands, 'perl', "-I$sock_root/lib", "$sock_root/tools/$tool";
  
  {
    my ( $stdin, $stdout );

    IPC::Run::run ( \@commands, \$stdin, \$stdout, init => sub {
      $ENV{$_} = $env->{$_} for keys %$env;
      
      chdir $session_path;
    } );
  }
  
  my $ok;
  
  if ( -f $log_file ) {
    if ( open my $fh, '<', $log_file ) {
      $ok = grep { m/Tool '$tool' done/ } <$fh>;
    }
    else {
      $log->yell ( "Could not open '$log_file' LOG file." );
    }
  }
  else {
    $log->yell ( "Could not find any '$log_file' LOG file." );
  }

  $log->left_n_say ( "Done." );
  
  $ok;
}

sub session_path { # FIXME factorize with iSOCK::Controller::Root::session_path
  my ( $package, $c ) = @_;
  
  my $session_path = $c->session->{session_path};
  
  unless ( $session_path && -d $session_path ) {
    _mkdir ( $session_path = $c->config->{directory}->{tmp} . '/' . $c->sessionid );
    
    $c->session->{session_path} = $session_path;
  }
  
  $session_path;
}

sub _mkdir { # FIXME factorize with iSOCK::Controller::Root::_mkdir
  my $dir = shift;
  
  system "mkdir -p $dir" unless -d $dir; # FIXME use File::Path instead
  
  $dir;
}

#
# True.
#

1;
